import { createRouter, createWebHashHistory } from 'vue-router'
import useUserStore from '@/stores/useUserStore.js'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: () => import('@/views/Home.vue'),
      redirect: '/index',
      children: [
        {
          path: '/index',
          name: 'Index',
          component: () => import('@/views/Index.vue'),
          meta: {
            permission: ['店长'],
            title: '经营分析',
            id: '1'
          }
        },
        {
          path: '/order-management',
          name: 'OrderManagement',
          component: () => import('@/views/OrderManagement.vue'),
          meta: {
            permission: ['店长'],
            title: '订单管理',
            id: '2'
          }
        },
        {
          path: '/dish-list',
          name: 'DishList',
          component: () => import('@/views/DishList.vue'),
          meta: {
            permission: ['店长'],
            title: '商品管理',
            id: '3'
          }
        },
        {
          path: '/add-product',
          name: 'AddProduct',
          component: () => import('@/views/AddProduct.vue'),
          meta: {
            permission: ['店长'],
            title: '新建商品',
            id: '3'
          }
        },
        {
          path: '/order-desk',
          name: 'OrderDesk',
          component: () => import('@/views/OrderDesk.vue'),
          meta: {
            permission: ['店长'],
            title: '堂食点餐',
            id: '4'
          }
        },
        {
          path: '/staff-management',
          name: 'StaffManagement',
          component: () => import('@/views/StaffManagement.vue'),
          meta: {
            permission: ['店长'],
            title: '员工管理',
            id: '5'
          }
        },
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue')
    },
  ]
})

router.beforeEach((to) => {
  const userStore = useUserStore()
  if (to.name === 'Login') {
    if (userStore.token) {
      return false
    }
  }
  else {
    if (!userStore.token) {
      return { name: 'Login' }
    }
    else {
      if (to.meta.hasOwnProperty('permission')) {
        if (!to.meta.permission.includes(userStore.user.employeeRole)) {
          return { name: 'Home' }
        }
      }
    }
  }
})

export default router